//
//  AppDelegate.m
//  EasyToTesco2.0
//
//  Created by 杨森 on 16/5/30.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "AppDelegate.h"
#import "MainTabBarController.h"
#import <CoreLocation/CoreLocation.h>
#import "LocationServeManager.h"
#import <AFNetworkActivityIndicatorManager.h>
#import "ReadWriteLocationCity.h"
#import "XGSetting.h"
#import "XGPush.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApi.h"
#import "WXApiManager.h"
#import "GuideController.h"
#import <UMSocialCore/UMSocialCore.h>
#import <Photos/Photos.h>
#import "ShopDetailsController.h"

#import "BaseNavigationController.h"

#import "EaseUI.h"
#import "AppDelegate+EaseMob.h"
#import "ChatListViewController.h"
#import "BaseNavigationController.h"
#import "EaseConversationListViewController.h"

//com.jack.EasyToTescoShop
@interface AppDelegate ()<CLLocationManagerDelegate,WXApiDelegate>

{
    NSString *_JudgeLocationNotificationStirng;
    
    NSString *_JudgeLocationNotification;
}

//判断app是否kill
@property(nonatomic,assign)BOOL isAppKill;

@property (nonatomic,strong)CLLocationManager *locationManager;
//记录粘贴板
@property(nonatomic,strong)NSMutableArray *pasteArray;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    NSString *apnsCertName = nil;
#if DEBUG
    apnsCertName = @"YLGW8DevPush";
#else
    apnsCertName = @"YLGW8DevPush";
#endif
    // 注册本地推送通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(JudgeLocationNotication:)
                                                 name:KNOTIFICATION_LOCATIONNOTICATION
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(JudgeLocationNoticationWithChat:) name:KNOTIFICATION_LOCATIONNOTICATIONVIEW object:nil];
    
    NSString *appkey = @"1191170519115328#dykw";
    
    [self easemobApplication:application didFinishLaunchingWithOptions:launchOptions appkey:appkey apnsCertName:apnsCertName otherConfig:@{kSDKConfigEnableConsoleLogger:[NSNumber numberWithBool:YES]}];
    
    NSString *appVer = [NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    
    NSString *lastVer = [userDefault objectForKey:@"app_version"];
        if ([appVer isEqualToString:lastVer]) {
//    if (NO) {
        self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        self.window.rootViewController = [[MainTabBarController alloc] init];
        [self.window makeKeyAndVisible];
    } else {
        self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        GuideController *guid = [[GuideController alloc] init];
        self.window.rootViewController = guid;
        [self.window makeKeyAndVisible];
    }
    
    
    // 1.3 把当前app的版本号重新写入到"偏好设置"中
    [userDefault setObject:appVer forKey:@"app_version"];
    
    // 同步一下
    [userDefault synchronize];
    
    //状态栏 NAVi颜色设置
    if ([UIDevice currentDevice].systemVersion.floatValue >= 7.0) {
        [[UINavigationBar appearance] setBarTintColor:UIColorFromRGB(0xf76300)];
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
        [[UINavigationBar appearance] setTitleTextAttributes:
         [NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],  NSForegroundColorAttributeName, [UIFont fontWithName:@ "HelveticaNeue-CondensedBlack" size:16.0], NSFontAttributeName, nil]];
    }
    
    [XGPush setAccount:@"123"];
    
    [[LocationServeManager sharedLocationServeManager] start];
    
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    
    [self setUMSocial];
    
    [self registerPushForIOS8];
    
//    [XGPush startApp:2200261144 appKey:@"IDT4L9K646LE"];
    
    [WXApi registerApp:WX_APPID];
    
    //高德地图
    [AMapServices sharedServices].apiKey = @"73a98426bae17b408d537d332000eb08";
    //开启 HTTPS 功能
    [[AMapServices sharedServices] setEnableHTTPS:YES];
    
    //判断当前网络状态
    [self judgeNetworkStatus];
    
    //相机权限
//    [PHPhotoLibrary requestAuthorization:nil];
    UIImageView *splash = [[UIImageView alloc] initWithFrame:self.window.bounds];
    splash.image = [UIImage imageNamed:@"欢迎页"];
    [self.window addSubview:splash];
    [UIView animateWithDuration:1.5 animations:^{
        CATransform3D transform = CATransform3DMakeScale(1.5, 1.5, 1.0);
        splash.layer.transform = transform;
        splash.alpha = 0.0;
    } completion:^(BOOL finished){
        [splash removeFromSuperview];
    }];
    
    //获取粘贴板内容
    [self getApplicationPasteStringHandle];
    
    if(!launchOptions)
    {
        NSLog(@"用户点击app启动");
    }else{
        
        NSURL *url = [launchOptions objectForKey:UIApplicationLaunchOptionsURLKey];
        if (url) {
            self.isAppKill = true;
        }
    }
    return YES;
}



- (void)judgeNetworkStatus
{
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager ] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case -1:
                NSLog(@"未知网络");
                break;
            case 0:
                NSLog(@"网络不可达");
                break;
            case 1:
                NSLog(@"GPRS网络");
                break;
            case 2:
                NSLog(@"wifi网络");
                break;
            default:
                break;
        }
        if(status ==AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi)
        {
            NSLog(@"有网");
        }else
        {
            NSLog(@"没有网");
            MBProgressHUD *hud = [MBProgressHUD showMessage:@"当前网络不佳" toView:self.window dimBackground:NO AndCompleteBlock:nil];
            [self.window addSubview:hud];
        }
    }];
}

// 友盟
- (void)setUMSocial {
    //打开日志
    [[UMSocialManager defaultManager] openLog:YES];
    
    //设置友盟appkey
    [[UMSocialManager defaultManager] setUmSocialAppkey:@"592fb519a40fa37a1c0013b8"];
    
    //设置微信的appKey和appSecret
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wxf9da143b364c4a6d" appSecret:@"64ab8e932011bffe9b216beda4f4c06e" redirectURL:@"http://www.593.com"];
    
    //设置新浪的appKey和appSecret
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:@"3338675522"  appSecret:@"41123ae16ee41b498d4d3c3c123f2d36" redirectURL:@"http://sns.whalecloud.com/sina2/callback"];
    
    // 设置分享到QQ互联的appID
    // U-Share SDK为了兼容大部分平台命名，统一用appKey和appSecret进行参数设置，而QQ平台仅需将appID作为U-Share的appKey参数传进即可。
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"1106121643"/*设置QQ平台的appID*/  appSecret:nil redirectURL:@"http://www.593.com"];
    

}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    
    if ([url.host isEqualToString:@"Product"]) {
        [self expandSnHandleOpenUrl:url];
        return YES;
    }
    
    BOOL isSuc = [WXApi handleOpenURL:url delegate:self];
    NSLog(@"url %@ isSuc %d",url,isSuc == YES ? 1 : 0);
    return  isSuc;
    
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
   
    if (result == FALSE) {
        //调用其他SDK，例如支付宝SDK等
        //如果极简开发包不可用，会跳转支付宝钱包进行支付，需要将支付宝钱包的支付结果回传给开发包
        if ([url.host isEqualToString:@"safepay"]) {
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
                //【由于在跳转支付宝客户端支付的过程中，商户app在后台很可能被系统kill了，所以pay接口的callback就会失效，请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】
                NSLog(@"result = %@",resultDic);
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"processOrderWithPaymentResult" object:resultDic];
                
            }];
        }
        if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回authCode
            
            [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
                //【由于在跳转支付宝客户端支付的过程中，商户app在后台很可能被系统kill了，所以pay接口的callback就会失效，请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】
                NSLog(@"result = %@",resultDic);
            }];
        }
        return YES;

    } else {
        return result;
    }
    
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    NSLog(@"%s",__func__);
    [self.mainController setupUnreadMessageCount];
    
    NSLog(@"%@",[ReadWriteLocationCity ReadLocatinoCity]);
    NSLog(@"%@",[ReadWriteLocationCity ReadLocationString]);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"locationCity" object:nil];
}

#pragma mark WeChatPay
-(void)onResp:(BaseResp *)resp{
    NSLog(@"%s",__func__);
    //如果第三方程序向微信发送了sendReq的请求，那么onResp会被回调。sendReq请求调用后，会切到微信终端程序界面
    NSString *strMsg=[NSString stringWithFormat:@"errcode:%d",resp.errCode];
    NSString *strTitle;
    if ([resp isKindOfClass:[PayResp class]]) {
        //支付返回结果，实际支付结果需要去微信服务器端查询
        strTitle=[NSString stringWithFormat:@"支付结果"];
        switch (resp.errCode) {
            case WXSuccess:
                strMsg=@"支付结果：成功！";
                break;
                
            default:
                strMsg = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                break;
        }
        NSLog(@"%@",strMsg);
        [[NSNotificationCenter defaultCenter] postNotificationName:@"WeChatType" object:resp];
    }
    //支付成功后回调
    // http://210.22.129.138:8080/link/public/notifywechatcallback
    
    //下边先注释掉，以后会用得上
    //    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    //    [alert show];
}



-(void)onReq:(BaseReq *)req{
    NSLog(@"%s",__func__);
    //onReq是微信终端向第三方程序发起请求，要求第三方程序响应。第三方程序响应完后必须调用sendRsp返回。在调用sendRsp返回时，会切回到微信终端程序界面
}



- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [WXApi handleOpenURL:url delegate:self];
}



#pragma mark  应用链接
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{

    if ([url.host isEqualToString:@"Product"]) {
        [self expandSnHandleOpenUrl:url];
        return YES;
    }
    
    if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            //【由于在跳转支付宝客户端支付的过程中，商户app在后台很可能被系统kill了，所以pay接口的callback就会失效，请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】
            NSLog(@"result = %@",resultDic);
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"processOrderWithPaymentResult" object:resultDic];
            
        }];
    }
    if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回authCode
        
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
            //【由于在跳转支付宝客户端支付的过程中，商户app在后台很可能被系统kill了，所以pay接口的callback就会失效，请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】
            NSLog(@"result = %@",resultDic);
        }];
    }

    
    return [WXApi handleOpenURL:url delegate:self];
}


#pragma mark 推送
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    //NSString * deviceTokenStr = [XGPush registerDevice:deviceToken];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        EMError *error = [[EMClient sharedClient] bindDeviceToken:deviceToken];
        NSLog(@"%@",error);
    });

    
    void (^successBlock)(void) = ^(void){
        //成功之后的处理
        NSLog(@"[XGPush Demo]register successBlock");
    };
    
    void (^errorBlock)(void) = ^(void){
        //失败之后的处理
        NSLog(@"[XGPush Demo]register errorBlock");
    };
    
    // 设置账号
    //
    
    //注册设备
    NSString * deviceTokenStr = [XGPush registerDevice:deviceToken successCallback:successBlock errorCallback:errorBlock];
    
    //如果不需要回调
    //[XGPush registerDevice:deviceToken];
    
    //打印获取的deviceToken的字符串
    NSLog(@"[XGPush Demo] deviceTokenStr is %@",deviceTokenStr);
}

// 注册deviceToken失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    NSLog(@"error -- %@",error);
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"apns.failToRegisterApns", Fail to register apns)
                                                    message:error.description
                                                   delegate:nil
                                          cancelButtonTitle:NSLocalizedString(@"好的", @"OK")
                                          otherButtonTitles:nil];
    [alert show];
}

- (void)registerPushForIOS8{
    
    //Types
    UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
    
    //Actions
    UIMutableUserNotificationAction *acceptAction = [[UIMutableUserNotificationAction alloc] init];
    
    acceptAction.identifier = @"ACCEPT_IDENTIFIER";
    acceptAction.title = @"Accept";
    
    acceptAction.activationMode = UIUserNotificationActivationModeForeground;
    acceptAction.destructive = NO;
    acceptAction.authenticationRequired = NO;

    //Categories
    UIMutableUserNotificationCategory *inviteCategory = [[UIMutableUserNotificationCategory alloc] init];
    
    inviteCategory.identifier = @"INVITE_CATEGORY";
    
    [inviteCategory setActions:@[acceptAction] forContext:UIUserNotificationActionContextDefault];
    
    [inviteCategory setActions:@[acceptAction] forContext:UIUserNotificationActionContextMinimal];
    
    NSSet *categories = [NSSet setWithObjects:inviteCategory, nil];
    
    
    UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:categories];
    
    [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
    
    
    [[UIApplication sharedApplication] registerForRemoteNotifications];
}


#pragma mark  app从后台进前台 获取粘贴板内容
- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [self getApplicationPasteStringHandle];
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    
}

//app将要结束时需要执行的操作
- (void)applicationWillTerminate:(UIApplication *)application
{
    //将存在本地的sn邀请码 销毁
    [[ExpandSnPlist shareExpandPlist] removePlist];
}


#pragma mark 通过url_scheme邀请码链接启动商品详情页
/**
 通过url_scheme邀请码链接启动商品详情页
 
 @param url 回调来的地址
 */
- (void)expandSnHandleOpenUrl:(NSURL *)url
{
//    NSLog(@"1:%@",url);
    //        NSLog(@"host:%@",url.host);
    
    //      dev.scheme.ylgw8://Product/index/id/357477/sn/598037
    
    NSString *urlPath = url.path;
    NSArray *array = [urlPath componentsSeparatedByString:@"/"];
//    NSLog(@"%@",array);
    NSString *productId = nil;
    NSString *expandSn = nil;

    
    if ([array containsObject:@"sn"]) {
        
        NSInteger idIndex = [array indexOfObject:@"id"];
        productId = [array objectAtIndex:idIndex+1];
        NSInteger snIndex = [array indexOfObject:@"sn"];
        expandSn = [array objectAtIndex:snIndex+1];
        
    }else{
        
        NSInteger idIndex = [array indexOfObject:@"id"];
        productId = [array objectAtIndex:idIndex+1];
        expandSn = @"0";
    }

    NSDictionary *dict = @{SN_PRODUCT_ID:productId,SN_EXPAND_ID:expandSn};
    [[ExpandSnPlist shareExpandPlist] writeToPlistWithDic:dict];

    [self custcomApplicationPushToShopDetailsControllerProductId:productId expandSn:expandSn];
}


/**
 获取粘贴板内容
 */
- (void)getApplicationPasteStringHandle
{
    UIPasteboard *paste = [UIPasteboard generalPasteboard];
    //判断是否符合链接格式
    if (![paste.string containsString:@"请您打开链接"]) return;
    //两条链接相同return
    [self.pasteArray addObject:paste.string];
    BOOL isResult = false;;
    if (self.pasteArray.count > 1) {
        NSInteger count = self.pasteArray.count-2;
        NSString *lastStr = [self.pasteArray lastObject];
        isResult = [lastStr isEqualToString:self.pasteArray[count]];
        //        NSLog(@"%d",isResult);
    }
    if (isResult)return;
    
    NSString *pasteStr = paste.string;
    NSRange range = [pasteStr rangeOfString:@"id"];
    NSInteger index = range.location;
    pasteStr = [pasteStr substringFromIndex:index];
    NSArray *array = [pasteStr componentsSeparatedByString:@"/"];
    //NSLog(@"%@",array);
    
    NSString *titleStr = paste.string;
    NSRange range1 = [titleStr rangeOfString:@",请"];
    NSInteger index1 = range1.location;
    titleStr = [titleStr substringToIndex:index1];
    
    NSString *productId = array[1];
    NSString *expandSn = [paste.string containsString:@"sn"] ? [array lastObject] : @"0";
    
    //sn写入
    NSDictionary *dict = @{SN_PRODUCT_ID:productId,SN_EXPAND_ID:expandSn};
    [[ExpandSnPlist shareExpandPlist] writeToPlistWithDic:dict];
    
    UIAlertController *alert1 = [UIAlertController alertControllerWithTitle:@"分享的商品链接" message:titleStr preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *SettingAction = [UIAlertAction actionWithTitle:@"立即查看" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {

        [self custcomApplicationPushToShopDetailsControllerProductId:productId expandSn:expandSn];
        
    }];
    [alert1 addAction:SettingAction];
    
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert1 addAction:cancleAction];
    
    [self.window.rootViewController presentViewController:alert1 animated:YES completion:nil];
}


/**
 获取到粘贴板内容或者url_scheme启动商品详情

 @param productId 商品id
 @param expandSn 商品sn
 */
- (void)custcomApplicationPushToShopDetailsControllerProductId:(NSString *)productId expandSn:(NSString *)expandSn
{
    MainTabBarController *mainTabBarVC = (MainTabBarController *)self.window.rootViewController;
    ShopDetailsController *shop = [[ShopDetailsController alloc] init];
    shop.goodsId = productId;
    shop.expand_sn = expandSn;
    shop.hidesBottomBarWhenPushed = YES;
    
    [mainTabBarVC.viewControllers[mainTabBarVC.selectedIndex] pushViewController:shop animated:true];

}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    
    NSLog(@"%@",notification);
    
    if (!_JudgeLocationNotificationStirng.length && !_JudgeLocationNotification.length) {
        UITabBarController *tabController = (UITabBarController *)self.window.rootViewController;
        
        BaseNavigationController *base = (BaseNavigationController *)tabController.viewControllers[tabController.selectedIndex];
        ChatListViewController *login = [ChatListViewController new];
        login.title = @"聊天列表";
        [base pushForm:base pushToAndHidden:login];
    }
}

- (void)easemobApplication:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    NSLog(@"%@",userInfo);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    [self easemobApplication:application didReceiveRemoteNotification:userInfo];
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    NSLog(@"%@",userInfo);
    if (userInfo.count) {
        UITabBarController *tabController = (UITabBarController *)self.window.rootViewController;
        
        BaseNavigationController *base = (BaseNavigationController *)tabController.viewControllers[tabController.selectedIndex];
        ChatListViewController *login = [ChatListViewController new];
        login.title = @"聊天列表";
        [base pushForm:base pushToAndHidden:login];
    }
    
    
}

- (void)JudgeLocationNotication:(NSNotification *)notification {
    _JudgeLocationNotificationStirng = [NSString stringWithFormat:@"%@",notification.object];
    NSLog(@"%@",_JudgeLocationNotificationStirng);
}

- (void)JudgeLocationNoticationWithChat:(NSNotification *)notification {
    _JudgeLocationNotification = [NSString stringWithFormat:@"%@",notification.object];
    NSLog(@"%@",_JudgeLocationNotification);
}

- (NSMutableArray *)pasteArray
{
    if (!_pasteArray) {
        _pasteArray = [NSMutableArray array];
    }
    return _pasteArray;
}

@end
